package com.galaxy.coupon.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.galaxy.coupon.domain.CouponTemplate;
import com.galaxy.coupon.domain.bo.CouponTemplateBo;
import com.galaxy.coupon.domain.convert.CouponTemplateConvert;
import com.galaxy.coupon.domain.vo.CouponTemplateVo;
import com.galaxy.coupon.mapper.CouponTemplateMapper;
import com.galaxy.coupon.service.ICouponTemplateService;
import com.galaxy.common.mybatis.core.page.PageQuery;
import com.galaxy.common.mybatis.core.page.TableDataInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

/**
 * 优惠券模板Service业务层处理
 */
@RequiredArgsConstructor
@Service
public class CouponTemplateServiceImpl implements ICouponTemplateService {

    private final CouponTemplateMapper baseMapper;

    @DS("slave")
    @Override
    public TableDataInfo<CouponTemplateVo> queryPage(CouponTemplateBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<CouponTemplate> lqw = buildQueryWrapper(bo);
        Page<CouponTemplateVo> page = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(page);
    }

    @DS("slave")
    @Override
    public CouponTemplateVo getInfo(Long id) {
        return baseMapper.selectVoById(id);
    }

    @Override
    public Boolean insertByBo(CouponTemplateBo bo) {
            CouponTemplate add = CouponTemplateConvert.INSTANCE.convert(bo);
            validEntityBeforeSave(add);
            boolean flag = baseMapper.insert(add) > 0;
            if (flag) {
                bo.setId(add.getId());
        }
        return flag;
    }

    @Override
    public Boolean updateByBo(CouponTemplateBo bo) {
        CouponTemplate update = CouponTemplateConvert.INSTANCE.convert(bo);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    @Override
    public Boolean deleteById(Long id) {
        return baseMapper.deleteById(id) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(CouponTemplate entity) {
        // TODO 做一些数据校验,如唯一约束
    }

    /**
     * 构建查询条件
     */
    private LambdaQueryWrapper<CouponTemplate> buildQueryWrapper(CouponTemplateBo bo) {
        LambdaQueryWrapper<CouponTemplate> lqw = new LambdaQueryWrapper<>();
        lqw.eq(bo.getId() != null, CouponTemplate::getId, bo.getId());
        lqw.like(bo.getName() != null, CouponTemplate::getName, bo.getName());
        lqw.eq(bo.getType() != null, CouponTemplate::getType, bo.getType());
        lqw.eq(bo.getStatus() != null, CouponTemplate::getStatus, bo.getStatus());
        return lqw;
    }
}
